# coding=utf-8
# author:xc
# datetime:2018/8/1 10:39

from dbConnection.MysqlConn import Mysql
from . import admin
from flask import render_template, request
from app import util, upload
import sys
from werkzeug.utils import secure_filename

reload(sys)
sys.setdefaultencoding('utf8')


@admin.route('/admin/store/list.html', methods=['POST', 'GET'])
@util.admin_login
def admin_store_list():
    try:
        page = request.args.get('page', default=1)
        page = int(page)
        num = (page - 1) * util.PAGE_NUM
        storeName = request.args.get('storeName')
        mysql = Mysql()
        sql = "select * from store where 1=1  "
        sql2 = "select count(*) from store  where 1=1 "
        if storeName != "" and storeName is not None:
            sql += " and locate('%s',storeName)" % storeName
            sql2 += " and locate('%s',storeName)" % storeName
        sql += " order by addTime desc  limit %d,%d " % (num, util.PAGE_NUM)
        result = mysql.getAll(sql, None)
        count = mysql.getOne(sql2, None)
        count = int(count['count(*)'])
        code = util.CODE_EMPTY
        data = []
        if count % util.PAGE_NUM > 0:
            max_page = count / util.PAGE_NUM + 1
        else:
            max_page = count / util.PAGE_NUM
        if result:
            code = util.CODE_SUCCESS
            data = result
        mysql.dispose()
        res = {
            'data': data,
            'page': page,
            'max_page': max_page,
            'code': code,
        }
        return render_template('admin/store/store_list.html', res=res)
    except Exception as e:
        print e


@admin.route('/admin/store/newly.html', methods=['POST', 'GET'])
@util.admin_login
def admin_store_newly():
    if request.method == "GET":
        return render_template('admin/store/store_newly.html')
    else:
        try:
            storeName = request.values.get('storeName')
            province = request.values.get('province')
            city = request.values.get('city')
            area = request.values.get('area')
            address = request.values.get('address')
            longitude = request.values.get('longitude')
            latitude = request.values.get('latitude')
            status = request.values.get('status')
            storeUrl = request.files['all_file']
            workTime = request.values.get('workTime')
            mysql = Mysql()
            res = mysql.getOne("select * from store  where storeName='%s'" % storeName, None)
            if res:
                code = util.CODE_EMPTY
            else:
                code = util.CODE_SUCCESS
                url = upload.upload(storeUrl)
                import MySQLdb
                sql = "insert into store (storeName,province,city,area,address, addTime,status,longitude,latitude,storeUrl,workTime)" \
                      " values ('%s','%s','%s','%s','%s',now(),'%s','%s','%s','%s','%s')" % (
                          storeName, MySQLdb.escape_string(province), MySQLdb.escape_string(city), area, address,
                          status, longitude, latitude, MySQLdb.escape_string(url), workTime)
                mysql.insertOne(sql, None)
            mysql.dispose()
        except Exception as e:
            print e
            code = util.CODE_ERROR
        data = {
            'code': code

        }
        return util.to_json(data)


@admin.route('/admin/store/stop', methods=['POST'])
@util.admin_login
def admin_store_stop():
    storeId = request.values.get('storeId')
    mysql = Mysql()
    sql = "update store set status=2 where storeId='%s'" % storeId
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status': 1
        }
    else:
        data = {
            'status': 0
        }
    return util.to_json(data)


@admin.route('/admin/store/start', methods=['POST'])
@util.admin_login
def admin_store_start():
    storeId = request.values.get('storeId')
    mysql = Mysql()
    sql = "update store set status=1 where storeId='%s'" % storeId
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status': 1
        }
    else:
        data = {
            'status': 0
        }
    return util.to_json(data)


@admin.route('/admin/store/delete', methods=['POST'])
@util.admin_login
def admin_store_delete():
    storeId = request.values.get('storeId')
    mysql = Mysql()
    sql = "delete from store where storeId='%s' " % storeId
    res = mysql.delete(sql, None)
    sql2 = "delete from car_machine where storeId='%s'" % storeId
    mysql.delete(sql2, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status': 1
        }
    else:
        data = {
            'status': 0
        }
    return util.to_json(data)


@admin.route('/admin/store/edit.html', methods=['POST', 'GET'])
@util.admin_login
def admin_store_edit():
    if request.method == "GET":
        storeId = request.args.get('storeId')
        mysql = Mysql()
        sql = "select * from  store where storeId='%s'" % storeId
        res = mysql.getOne(sql, None)
        mysql.dispose()
        return render_template('admin/store/store_edit.html', res=res)
    else:
        try:
            storeId = request.values.get('storeId')
            storeName = request.values.get('storeName')
            workTime = request.values.get('workTime')
            flag = request.values.get('flag')
            mysql = Mysql()
            code = util.CODE_EMPTY
            if int(flag) == 1:
                storeUrl = request.files['all_file']
                url = upload.upload(storeUrl)
                sql = "update store set storeName='%s',workTime='%s',storeUrl='%s' where storeId='%s' " % (
                    storeName, workTime, url, storeId)
                res = mysql.update(sql, None)
                if res > 0:
                    code = util.CODE_SUCCESS
            else:
                sql = "update store set storeName='%s',workTime='%s' where storeId='%s' " % (
                    storeName, workTime, storeId)
                res = mysql.update(sql, None)
                if res > 0:
                    code = util.CODE_SUCCESS
            mysql.dispose()
        except Exception as e:
            print e
            code = util.CODE_ERROR
        data = {
            'code': code
        }
        return util.to_json(data)
